<script setup>
import { ref } from 'vue'
import { NInput, NButton } from 'naive-ui'
import { computed } from 'vue'

const newTodo = ref('')
// 待办事项列表（带初始示例数据）
const todoList = ref([
  {id: 1, text: '学习Vue', completed: false},
  {id: 2, text: '完成练习', completed: false}
])

// 新增待办事项（带非空校验）
const addTodo = () => {
  if (newTodo.value.trim()) {
    todoList.value.push({
      id: Date.now(), // 使用时间戳作为唯一ID
      text: newTodo.value.trim(),
      completed: false
    })
    newTodo.value = '' // 清空输入框
  }
}

// 删除待办事项
const deleteTodo = (id) => {
  todoList.value = todoList.value.filter(item => item.id !== id)
}

// 计算已完成的数量
const completedCount = computed(() => {
  return todoList.value.filter(item => item.completed).length;
});

// 计算未完成的数量
const activeCount = computed(() => {
  return todoList.value.filter(item => !item.completed).length;
});
// 切换任务完成状态
const toggleComplete = (id) => {
  const todo = todoList.value.find(item => item.id === id);
  if (todo) {
    todo.completed = !todo.completed;
  }
};
</script>

<template>
  <div class="container">
    <h1>待办事项</h1>
    <div class="stats">
      <span>已完成: {{ completedCount }}</span>
      <span>未完成: {{ activeCount }}</span>
    </div>
    <div class="input-group">
      <n-input v-model:value="newTodo"
             @keyup.enter="addTodo"
             placeholder="输入待办事项"
             class="todo-input"/>
      <n-button @click="addTodo" class="add-btn" type="primary">添加</n-button>
    </div>

    <div v-if="todoList.length" class="todo-list">
      <div v-for="item in todoList" :key="item.id" class="todo-item">
        <!-- 点击切换完成状态 -->
        <span
            @click="toggleComplete(item.id)"
            :style="{ textDecoration: item.completed ? 'line-through' : 'none' }"
        >
          {{ item.text }}
        </span>
        <n-button @click="deleteTodo(item.id)" class="delete-btn" type="error">
          删除
        </n-button>
      </div>
    </div>
    <p v-else class="empty-tip">暂无待办事项</p>
  </div>
</template>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.todo-input {
  flex: 1;
}

.add-btn {
  white-space: nowrap;
}

.todo-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: white;
}

.todo-item:last-child {
  border-bottom: none;
}

.todo-item span {
  flex: 1;
}

.empty-tip {
  text-align: center;
  color: #888;
  font-style: italic;
  margin-top: 20px;
}
</style>
